/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

/**
 *
 * @author Jefferson
 */
public class DAOGenerico {
    protected HibernateConfig hibernateConfig;
    
    public DAOGenerico() {
      hibernateConfig = new HibernateConfig();
    }
    
    public void inserir(Object obj) throws HibernateException {
        Session session = hibernateConfig.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(obj);
        transaction.commit();
        session.close();
    }
    
    public void alterar(Object obj) throws HibernateException {
        Session session = hibernateConfig.openSession();
        Transaction transaction = session.beginTransaction();
        session.update(obj);
        transaction.commit();
        session.close();
    }
    
    public void excluir(Object obj) throws HibernateException {
        Session session = hibernateConfig.openSession();
        Transaction transaction = session.beginTransaction();
        session.delete(obj);
        transaction.commit();
        session.close();
    }
    
    public List listarTodos(Class clas, String ordem) throws HibernateException {
        Session session = hibernateConfig.openSession();
        Criteria criteria = session.createCriteria(clas);
        criteria.addOrder(Order.asc(ordem));
        List lista = criteria.list();
        session.close();
        return lista;
    }
    
    public Object carregar(int id, Class clas) throws HibernateException {
        Session session = hibernateConfig.openSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(clas);
        criteria.add(Expression.eq("id", id));
        Object obj = criteria.uniqueResult();
        transaction.commit();
        session.close();
        return obj;
    }
}